// pages/signCard/signCard.js
const app = getApp()
var QR = require("../../utils/qrcode.js");
var utils = require("../../utils/utils.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imagePath: '',
    ewmPath: '',
    ewmHidden: false,
    imageHidden: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      activityChildId: options.activityChildId
    })
    if (!app.isLogin()) {
      this.getUserInfo();
    } else {
      this.initData();
    }
  },
  initData: function(){
    // 页面初始化 options为页面跳转所带来的参数
    var size = this.setCanvasSize();//动态设置画布大小
    var initUrl = "http://m.xue110.top/hm/parentSign?activityChildId=" + this.data.activityChildId + "&parentId=" + app.globalData.appUser.userInfo.id;
    this.createQrCode(initUrl, "ewmcanvas", size.w, size.w);
  },
  querySignInfo: function() {
    var that = this;
    wx.request({
      url: app.httpUrl + '/user/getSignInfo',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      data: {
        activityChildId: this.data.activityChildId
      },
      method: "POST",
      success: (res) => {
        if (res.data.code == '000') {
          var signInfo = res.data.data;
          signInfo.startDate = utils.formatDate(signInfo.activityStartDate, 'Y/M/D h:m');
          signInfo.endDate = utils.formatDate(signInfo.activityEndDate, 'M/D h:m');
          that.setData({
            signInfo: signInfo
          })
          that.drawCard(signInfo);
        }
      }
    })
  },
  previewImage: function () {
    wx.canvasToTempFilePath({
      canvasId: 'canvas',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        console.log(tempFilePath);
        wx.previewImage({
          current: tempFilePath, // 当前显示图片的http链接  
          urls: [tempFilePath] // 需要预览的图片http链接列表  
        })
      },
      fail: function (res) {
        console.log(res);
      }
    });

  },
  drawCard: function (data) {
    var res = wx.getSystemInfoSync();
    var cxt = wx.createContext()
    cxt.setFillStyle('#fff');
    cxt.fillRect(1, 1, res.windowWidth-2, 580)
    this.canvasTextAutoLine(data.activityName, cxt, 10, 30, 18, "#2ab257");
    cxt.setFontSize(15);
    cxt.fillStyle = "#959595";
    cxt.fillText("活动时间：" + data.startDate + "-" + data.endDate, 10, 68);
    cxt.fillText("活动地址：" + data.activityAddr, 10, 88);
    cxt.fillText("宝贝姓名：" + data.childName, 10, 108);
    cxt.fillText("联系电话：" + data.parentMobile, 10, 128);
    cxt.drawImage(this.data.ewmPath, ((res.windowWidth-300)/2), 148, 300, 300);
    cxt.font = "BOLD 15px 黑体";
    cxt.fillText("温馨提示", 10, 500);
    this.canvasTextAutoLine("1.请不要把二维码随意分享给他人", cxt, 10, 520, 15, "#999");
    this.canvasTextAutoLine("2.开营签到、结营签到请打开此页，调亮手机屏幕，提供给现场助教扫描确认身份", cxt, 10, 540, 15, "#999");

    wx.drawCanvas({
      canvasId: 'canvas',
      actions: cxt.getActions()
    })
    //setTimeout(() => { this.canvasToTempImage(); }, 1000);
  },
  canvasTextAutoLine: function(str, ctx, initX, initY, fsize, fstyle){
    var res = wx.getSystemInfoSync();
    var lineHeight = 18;
    var lineWidth = 0;
    var canvasWidth = res.windowWidth;
    var lastSubStrIndex = 0;
    for(let i = 0;i<str.length;i++){
      lineWidth += ctx.measureText(str[i]).width;
      ctx.setFontSize(fsize);
      ctx.fillStyle = fstyle;
      if (lineWidth > canvasWidth - (initX + 20)) {
        ctx.fillText(str.substring(lastSubStrIndex, i), initX, initY);
        initY += lineHeight;
        lineWidth = 0;
        lastSubStrIndex = i;
      }
      if (i == str.length - 1) {
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), initX, initY);
      }
    }
	},
  //适配不同屏幕大小的canvas
  setCanvasSize: function () {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 750 / 686;//不同屏幕下canvas的适配比例；设计稿是750宽
      var width = res.windowWidth / scale;
      var height = width;//canvas画布为正方形
      size.w = width;
      size.h = height;
    } catch (e) {
      // Do something when catch error
      console.log("获取设备信息失败" + e);
    }
    return size;
  },
  createQrCode: function (url, canvasId, cavW, cavH) {
    console.log("-w:" + cavW + "-H:" + cavH);
    //调用插件中的draw方法，绘制二维码图片
    QR.api.draw(url, canvasId, cavW, cavH);
    setTimeout(() => { this.canvasToTempEwm(); }, 500);
  },
  //获取临时缓存照片路径，存入data中
  canvasToTempEwm: function () {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'ewmcanvas',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        console.log(tempFilePath);
        that.setData({
          ewmPath: tempFilePath,
          ewmHidden: true
        });
        that.querySignInfo();
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  canvasToTempImage: function() {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'canvas',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        console.log(tempFilePath);
        that.setData({
          imagePath: tempFilePath,
          imageHidden: true
        });
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  getUserInfo: function (options) {
    let that = this;
    if (app.globalData.appUser != null) {
      return;
    }
    wx.login({
      success: function (res) {
        console.log("---res.code=" + res.code);
        if (res.code) {
          //发起网络请求
          wx.request({
            url: app.httpUrl + '/common/getUserInfo',
            data: {
              code: res.code
            },
            header: {
              'content-type': 'application/json' // 默认值
            },
            method: "POST",
            success: function (res) {
              console.log("---getUser = " + JSON.stringify(res.data));
              if (res.data.code == '000') {
                app.globalData.appUser = res.data.data;
                app.globalData.openid = res.data.data.openid;
                that.initData();
              }
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
  }
})